<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页面</title>
    <link rel="stylesheet" href="./css/main.css">
    <link rel="stylesheet" href="./font-friends/iconfont.css">
</head>

<body>
    <div class="container">
        <div class="extra">
            <img class="user-icon" src="./favicon.ico">
            <div onclick="goToMessage()" class="iconfont icon-xiaoxi-2"></div>
            <div onclick="goToFriends()" class="iconfont icon-icon_huabanfuben"></div>
            <div onclick="goToGroup()" class="iconfont icon-qunliao"></div>
            <div onclick="goToPyq()" class="iconfont icon-pengyouquan"></div>
        </div>
        <div id="user-list" class="left">
            <div class="search-div">
                <img style="position: absolute;left: 20px" src="./img/search.png">
                <input placeholder="搜索" onclick="resetInput(this)" oninput="searchMessage(this)" class="search-input">
                <img onclick="unsetInput(this.parentNode)" id="x" src="./img/x.png">
                <div onclick="openModal()" style="line-height: 23px;font-weight: 10;font-size: 22px;cursor: pointer;border-radius: 2px;padding: 1.5px;background-color: #eeeeee;width: 23px;" >+</div>
            </div>
            <div class="user-item selected"  onclick="group(this)">
                <img class="user-avatar" src="./favicon.ico">
                <div class="user-name">群聊</div>
            </div>
        </div>
        <div class="right">
            <div id="title" class="title">
                群聊
            </div>
            <div id="content" class="content">
<!--                <div class="message own">-->
<!--                    <div class="name">我</div>-->
<!--                    <div class="own-message">4544</div>-->
<!--                </div>-->

            </div>

            <div class="send" onkeydown="handleKeyDown(event)">
                <textarea id="message-content"></textarea>
                <button onclick="send()" class="send-button">
                    发送
                </button>
            </div>

        </div>
    </div>

    <button onclick="cc()" id="exit">
        退出登录
    </button>

    <div class="context-menu" id="contextMenu">
        <ul>
            <li>撤回消息</li>
        </ul>
    </div>

    <div id="messageBox" class="message-box"></div>


    <div id="myModal" class="overlay" style="display: none;">
        <div class="modal">
            <h2>创建群聊</h2>
            <input type="text" id="groupName" placeholder="输入群聊名"><br><br>
            <button onclick="confirm()">确定</button>
            <button onclick="cancel()">取消</button>
        </div>
    </div>
</body>


</html>
<script src="./js/main.js"></script>
<script>
    var toName = "";
    var result;
    var username = localStorage.getItem("username");
    var ws; // websocket连接
    function group(element) {

        const items = document.querySelectorAll('.user-item');
        items.forEach(item => item.classList.remove('selected'));
        element.classList.add('selected')

        document.getElementById("title").innerText = "群聊";
        toName = "";
        ws = new WebSocket("ws://localhost/chat")

        // 给ws绑定事件
        ws.onopen = function () {
            // 显示在线信息
            // alert("websocket open!!!")
        }
        // 客户端接收到服务端推送的消息后触发
        ws.onmessage = function (event) {
            var data = event.data;

            result = JSON.parse(data);
            if (result.fromName == undefined) {
                // 发送的是撤回的信令 然后就根据time遍历删除
                var messages = document.querySelectorAll('.other-message');
                messages.forEach(function(message) {
                    var messageData = message.dataset.value;
                    if (messageData) {
                        var messageResult = JSON.parse(messageData);
                        if (messageResult.time == data) {
                            message.parentNode.style.display = 'none';
                        }
                    }
                });
            }

            var html;
            if (result.fromName == username) {

                // 这个就是初始化页面的时候 才会发生这种情况
                html = "<div class=\"message own\"><div class=\"name\">我</div><div data-value="+ data +" class=\"own-message\">"+ result.message +"</div></div>"
                //把定义的html语句，添加到页面上
            } else if (result.fromName == undefined) {
                return
            } else {
                html = "<div class=\"message other\"><div class=\"name\">"+ result.fromName +"</div><div data-value="+ data +" class=\"other-message\">"+ result.message +"</div></div>"
            }

            document.getElementById("content").innerHTML += html;
            var content = document.getElementById("content");
            content.scrollTop = content.scrollHeight;
        }
        ws.onclose = function () {
            // 显示离线信息
            // alert("websocket close!!!")
            // console.log("websocket close!!!")
        }
        // ws.send("init");
    }
    function showChat(name,note,element) {
        const items = document.querySelectorAll('.user-item');
        items.forEach(item => item.classList.remove('selected'));
        element.classList.add('selected')
        document.getElementById("title").innerText = note;
        toName = name;
        document.getElementById("content").innerText = "";
        ws = new WebSocket("ws://localhost/ptop");
        // 给ptop绑定事件
        ws.onopen = function() {
            // 当连接打开后，发送消息
            ws.send(name);
        };
        // 客户端接收到服务端推送的消息后触发
        ws.onmessage = function (event) {
            var data = event.data;
            result = JSON.parse(data);
            if (result.fromName == undefined) {
                // 发送的是撤回的信令 然后就根据time遍历删除
                var messages = document.querySelectorAll('.other-message');
                messages.forEach(function (message) {
                    var messageData = message.dataset.value;
                    if (messageData) {
                        var messageResult = JSON.parse(messageData);
                        if (messageResult.time == data) {
                            message.parentNode.style.display = 'none';
                        }
                    }
                });
            }

            // var current = document.querySelector('.selected .user-name').innerText
            var html;
            if (result.fromName == username) {
                // 这个就是初始化页面的时候 才会发生这种情况
                html = "<div class=\"message own\"><div class=\"name\">我</div><div data-value=" + data + " class=\"own-message\">" + result.message + "</div></div>"
                //把定义的html语句，添加到页面上
            } else if (result.fromName == name) {
                html = "<div class=\"message other\"><div class=\"name\">" + note + "</div><div data-value=" + data + " class=\"other-message\">" + result.message + "</div></div>"
            } else {
                return;
            }
            document.getElementById("content").innerHTML += html;
            var content = document.getElementById("content");
            content.scrollTop = content.scrollHeight;
        }
    }
    // fetch('http://hanfeiyu.free.idcfengye.com/user/login', {


    init();
    function init() {
        fetch(`http://localhost/message/getMessageList?username=${username}`, {
            method: 'GET', // 指定请求方法为 GET
            headers: {
                'Content-Type': 'application/json',// 指定请求头
                'Authorization': localStorage.getItem("token")
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.flag) {
                    const userListDiv = document.getElementById('user-list');
                    data.data.forEach(object=> {
                        if (object.note == null) {
                            object.note = object.friend_name;
                        }
                        const userItemHtml = `
                            <div onclick="showChat('${object.friend_name}','${object.note}',this)" class="user-item">
                                <img class="user-avatar" src="./favicon.ico">
                                <div class="user-name">${object.note}</div>
                            </div>
                        `;
                        // 将用户条目的 HTML 添加到 userListDiv 中
                        if (object.friend_name != username) {
                            userListDiv.innerHTML += userItemHtml;
                        }
                    });

                }else {
                    alert('获取消息失败，' + data.message)
                    console.error('获取消息失败:', data.message);
                }
            })
            .catch(error => {
                console.error('获取消息请求出现问题:', error);
                alert('您尚未登录，请先登录！');
                localStorage.clear();
                window.location.href = 'login.html'
            });
    }


    // 朋友页面跳转用




    //绑定enter键 发送消息
    function handleKeyDown(event) {

        if (event.keyCode === 13) {
            event.preventDefault();
            send();
        }
    }


    //把消息发送到后端
    function send() {
        var message = document.getElementById("message-content").value.trim();
        if (message == "") {
            //这里要在<div class="send">这个容器的右下角，显示不能发送空白消息
            var warningMessage = document.createElement("div");
            warningMessage.textContent = "不能发送空白消息";
            warningMessage.classList.add("warning-message");
            document.querySelector(".send").appendChild(warningMessage);
            setTimeout(function() {
                warningMessage.remove();
            }, 2000);
            return;
        }

        var userList = document.getElementById('user-list');
        var selectedItem = document.querySelector('.selected');
        let secondUserItem = document.querySelector('.user-item').nextElementSibling;
        // 就是你调用方法的时候就放到前面，但在数据库里没有该顺序
        userList.insertBefore(selectedItem, secondUserItem);

        document.getElementById("message-content").value = "";

        // 因为有了撤回消息的系统 前端的信息上要含有value，value必须后端生成
        // var str = "<div class=\"message own\"><div class=\"name\">我</div><div data-value="+ JSON.stringify(result) +" class=\"own-message\">"+ message +"</div></div>"
        //把定义的html语句，添加到页面上
        // document.getElementById("content").innerHTML += str;
        //这个搞了一个发消息的时候 到最底部
        var content = document.getElementById("content");
        content.scrollTop = content.scrollHeight;

        if (toName == "") {
            ws.send(message);
        } else {
            var json = {"toName":toName,"message":message};
            ws.send(JSON.stringify(json));
        }


    }



    // 用户名
    // document.getElementById("username").innerHTML = username;
    function cc() {
        localStorage.clear();
        alert("退出成功！！！")
        window.location.href = 'login.html';
    }


    // 创建webSocket对象
    // var ws = new WebSocket("ws://hanfeiyu.free.idcfengye.com/chat")
    ws = new WebSocket("ws://localhost/chat")

    // 给ws绑定事件
    ws.onopen = function () {
        // 显示在线信息
        // alert("websocket open!!!")
    }
    // 客户端接收到服务端推送的消息后触发
    ws.onmessage = function (event) {
        var data = event.data;
        var html;

        result = JSON.parse(data);
        if (result.fromName == undefined) {
            // 发送的是撤回的信令 然后就根据time遍历删除
            var messages = document.querySelectorAll('.other-message');
            messages.forEach(function(message) {
                var messageData = message.dataset.value;
                if (messageData) {
                    var messageResult = JSON.parse(messageData);
                    if (messageResult.time == data) {
                        message.parentNode.style.display = 'none';
                    }
                }
            });
        }

        if (result.fromName == username) {
            // 这个就是初始化页面的时候 才会发生这种情况
            html = "<div class=\"message own\"><div class=\"name\">我</div><div data-value="+ data +" class=\"own-message\">"+ result.message +"</div></div>"
            //把定义的html语句，添加到页面上
        }  else if (result.fromName == undefined) {
            return;
        } else {
            html = "<div class=\"message other\"><div class=\"name\">"+ result.fromName +"</div><div data-value="+ data +" class=\"other-message\">"+ result.message +"</div></div>"
        }



        document.getElementById("content").innerHTML += html;
        var content = document.getElementById("content");
        content.scrollTop = content.scrollHeight;
    }
    ws.onclose = function () {
        // 显示离线信息
        // alert("websocket close!!!")
        // console.log("websocket close!!!")
    }



    // 判断本地存储中是否有 token
    const token = localStorage.getItem('token');

    if (token) {

    } else {
        alert('您尚未登录，请先登录！');
        window.location.href = 'login.html'; // 跳转到登录页面
    }




    setTimeout(function() {
        var url2 = window.location.href;
        var temp2 = url2.split('?')[1];
        var params = new URLSearchParams('?'+temp2);

        var point = params.get('point');
        var real = params.get('real');
        if (point == null && real == null) {
            return;
        }
        var find = false;
        document.querySelectorAll(".user-name").forEach(
            v => {
                if (v.innerText == point) {
                    find = true;
                }
            }
        )
        if (!find) {
            const messageData = {
                username: username,
                message_name: point
            }

            // 发请求新增一个
            fetch('http://localhost/message/addMessage', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem("token")
                },
                body: JSON.stringify(messageData)
            }).then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json(); // 解析响应的JSON数据
            })
                .then(data => {
                    if (data.flag) {
                        console.log('增添信息成功');
                    } else {
                        console.log('增添信息失败');
                    }
                })
                .catch(error => {
                    // 处理请求过程中的错误
                    console.error('请求出现问题:', error);
                });


        }
        var element = false;
        document.querySelectorAll(".user-name").forEach(
            v => {
                if (v.innerText == point) {
                    element = v.parentNode
                    element = true;
                }
            }
        )
        if (!element) {
            // 创建一条信息 todo
            const userListDiv = document.getElementById('user-list');
            const userItemHtml = `
                            <div onclick="showChat('${real}','${point}',this)" class="user-item">
                                <img class="user-avatar" src="./favicon.ico">
                                <div class="user-name">${point}</div>
                            </div>
                        `;
            // 将 HTML 字符串直接插入到 DOM 中
            userListDiv.insertAdjacentHTML('beforeend', userItemHtml);
            // 获取插入的元素，即最后一个子元素
            const userItem = userListDiv.lastElementChild;
            element = userItem;
        }


        var currentUrl = window.location.href;
        // 清除 URL 参数
        var cleanUrl = currentUrl.split('?')[0];
        // 修改 URL，不刷新页面
        window.history.pushState({}, document.title, cleanUrl);
        showChat(real, point, element);
    }, 100);




    document.addEventListener('contextmenu', function(event) {
        var target = event.target;
        if (target && target.classList.contains('own-message')) {
            event.preventDefault();
            var contextMenu = document.getElementById('contextMenu');
            contextMenu.style.left = event.pageX + 'px';
            contextMenu.style.top = event.pageY + 'px';
            contextMenu.style.display = 'block';
            document.querySelector('li').addEventListener('click', function() {
                var element = event.target;
                // 执行撤回的方法
                var result = element.dataset.value;

                // 获取消息的时间戳
                var messageTime = parseInt(JSON.parse(result).time);
                // 获取当前时间的时间戳
                var currentTime = Math.floor(Date.now());
                // 计算时间差（单位：秒）
                var timeDifference = (currentTime - messageTime)/1000;

                // 如果时间差大于两分钟（120秒），则进行提醒
                if (timeDifference > 120) {
                    document.getElementById("messageBox").innerText = "已经超过两分钟，无法撤回消息！";
                    showMessageBox();
                } else {
                    ws.send(result);
                    target.parentNode.style.display = 'none';
                    document.getElementById("messageBox").innerText =  "你撤回了一条消息";
                    showMessageBox();
                }
            });
        }
    });

    document.querySelector("body").addEventListener('click', function(event) {
        var contextMenu = document.getElementById('contextMenu');
        contextMenu.style.display = 'none';
    });



</script>
